from flask import request, jsonify, g, session

from app import db
from app.models.models import Comment

from app.utils.common.common import login_user_data
from . import chg_blu


@chg_blu.route("/comment", methods=["POST"])
@login_user_data
def comment():
    # 1. 提取出用户评价时的数据
    print("123456")
    print("123", request.json)
    content = request.json.get("content")
    cartoon_id = request.json.get("chg_id")
    parent_id = request.json.get("parent_id")
    
    if not all([content, cartoon_id]):
        ret = {
            "errno": 5005,
            "errmsg": "缺少参数"
        }
        return jsonify(ret)
    print("------------1")
    # 2. 将数据向数据库中插入
    try:
        print("------------2")
        c = Comment()
        print("------------3")
        c.cartoon_id = cartoon_id
        print("------------4")
        c.user_id = g.user.id
        print("------------5")
        c.content = content
        print("------------6")
        if parent_id:
            c.parent_id = parent_id
        db.session.add(c)
        print("------------7")
        db.session.commit()
        ret = {
            "errno": 0,
            "errmsg": "评论成功"
        }
        return jsonify(ret)
    except Exception as ret:
        ret = {
            "errno": 5006,
            "errmsg": "评论失败,请查看是否登录"
        }

        return jsonify(ret)


@chg_blu.route("/logout", methods=["POST"])
def logou():
    # 清空session完成退出功能
    session.clear()

    ret = {
        "errno": 0,
        "errrmsg": "退出成功"
    }
    return jsonify(ret)
